import React,{Component} from 'react';
import PropTypes from 'prop-types';
/**
 * 根据窗口大小进行相应组件的切换来实现响应式布局
 * @param desktop pc端加载的组件,为true或者false时都表示不加载改组件
 * @param phone   移动端加载的组件，为true或者false时都表示不加载改组件
 * @param size    移动端与pc端的分界点的窗口尺寸
 * @param exeJudgment 在进行请求时，会出现数据不更新的现象，通过设置exeJudgment来通知相应组件更新数据
 */
class Adaptive extends Component{
    constructor(props){
        super(props)
        this.state = {
            disComponent:window.innerWidth<props.size?props.phone:props.desktop
        }
    }
    judgmentComponent = () => {
        if(this.container) {
            let windowWith = window.innerWidth;
            let props = this.props;
            let size = this.props.size;
            this.setState({
                disComponent: windowWith < size ? props.phone : props.desktop
            })
        }
    }
    componentDidMount(){
        window.addEventListener('resize',this.judgmentComponent)
    }
    componentWillUnmount(){
        window.removeEventListener('resize',this.judgmentComponent)
    }
    componentWillReceiveProps(nextProps){
        if(nextProps.exeJudgment){
            this.judgmentComponent();
        }
    }
    render(){
        return(
            <div ref={(box)=>this.container=box}>{this.state.disComponent}</div>
        )
    }
}
export default Adaptive;
Adaptive.propTypes = {
    desktop:PropTypes.oneOfType([
        PropTypes.element,
        PropTypes.bool
    ]).isRequired,
    phone:PropTypes.oneOfType([
        PropTypes.element,
        PropTypes.bool
    ]).isRequired,
    size:PropTypes.number.isRequired,
    exeJudgment:PropTypes.bool
};